package xuperchain

import (
	"encoding/json"
	"fmt"
	"strconv"

	"github.com/xuperchain/xuper-sdk-go/v2/account"
	"github.com/xuperchain/xuper-sdk-go/v2/xuper"
)

func GetFileListLength() (result int) {
	type ListLengthResponse struct {
		Length string `json:"0"`
	}
	var totalFiles int

	account, err := account.GetAccountFromFile(path, pwd)
	if err != nil {
		fmt.Printf("GetAccountFromFile err: %v\n", err)
		panic(err)
	}

	err = account.SetContractAccount(contractAccount)
	if err != nil {
		panic(err)
	}

	xchainClient, err := xuper.New(nodeAddress)
	if err != nil {
		panic(err)
	}

	contractName := "xc_filestorage8"

	//获取文件个数
	txgetFileListLength, err := xchainClient.QueryEVMContract(account, contractName, "getFileListLength", nil)
	if err != nil {
		panic(err)
	}

	// 解析文件总数
	var response []ListLengthResponse
	err = json.Unmarshal([]byte(txgetFileListLength.ContractResponse.Body), &response)
	if err != nil {
		panic(err)
	}

	// 确保解析出来的数组中有一个元素
	if len(response) > 0 {
		totalFiles, err = strconv.Atoi(response[0].Length)
		if err != nil {
			panic(err)
		}
	} else {
		panic("No data returned")
	}

	return totalFiles
}
